package com.example.ysdt.controller;

import com.example.ysdt.Vo.ProductVo;
import com.example.ysdt.entiey.Product;
import com.example.ysdt.service.FileService;
import com.example.ysdt.service.ProductService;
import com.example.ysdt.utils.FolderToZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


@Configuration
@RestController
@RequestMapping("/Product")
@Api(value = "商品接口", tags = {"商品接口"})
public class ProductController {
    @Autowired
    ProductService productService;

    @Autowired
    FileService fileService;

    @PostMapping("queryProduct")
    @ApiOperation("查询商品")
    public Map<String, Object> queryCategory(@RequestBody ProductVo productVo) {
        Map<String, Object> Result = new HashMap<>();
        try {
            List<Product> products = productService.queryProduct(productVo);
            Result.put("code", 0);
            Result.put("message", "查询成功");
            Result.put("data", products);
        } catch (Exception e) {
            Result.put("code", -1);
            Result.put("message", "查询失败" + e.getMessage());
        }
        return Result;
    }

    @PostMapping("createProduct")
    @ApiOperation("上架商品")
    public Map<String, Object> count(@RequestBody Product product) {
        Map<String, Object> Result = new HashMap<>();
        try {
            productService.createProduct(product);
            Result.put("code", 0);
            Result.put("message", "提交成功，待审核中");
            Result.put("data", product);
        } catch (Exception e) {
            Result.put("code", -1);
            Result.put("message", "提交失败" + e.getMessage());
        }
        return Result;
    }

    @PostMapping("deleteProduct")
    @ApiOperation("删除商品")
    public Map<String, Object> deleteProduct(@RequestBody ProductVo productVo) {
        Map<String, Object> Result = new HashMap<>();
        try {
            productService.deleteProduct(productVo);
            List<Product> products = productService.queryProduct(new ProductVo());
            Result.put("code", 0);
            Result.put("message", "删除成功");
            Result.put("data", products);
        } catch (Exception e) {
            Result.put("code", -1);
            Result.put("message", "删除失败，" + e.getMessage());
        }
        return Result;
    }

    @PostMapping("updateStatus")
    @ApiOperation("审核状态")
    public Map<String, Object> Confim(@RequestBody ProductVo productVo) {
        Map<String, Object> Result = new HashMap<>();
        try {
            productService.productUpdate(productVo);
            Result.put("code", 0);
            Result.put("message", "审核完成");
        } catch (Exception e) {
            Result.put("code", -1);
            Result.put("message", "审核失败" + e.getMessage());
        }
        return Result;
    }

    @PostMapping("uploadImage")
    @ApiOperation("图片上传")
    public Map<String, Object> uploadImage(@RequestParam(value = "file", required = false) MultipartFile file, String randomStr) {
        Map<String, Object> result = new HashMap<>();

        // 1. 参数校验
        if (file == null || file.isEmpty()) {
            result.put("code", -1);
            result.put("message", "未提供有效文件");
            return result;
        }

        if (randomStr == null || randomStr.isEmpty()) {
            result.put("code", -1);
            result.put("message", "未提供随机字符串");
            return result;
        }

        // 2. 生成唯一文件夹路径
        String basePath = "C:/Users/Administrator/Desktop/productImages/";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String timestamp = sdf.format(new Date());
        String folderPath = basePath + timestamp + "_" + randomStr + "/";

        File folder = new File(folderPath);
        if (folder.exists()) {
            if (folder.isDirectory()) {
                System.out.println("目录已存在");
            } else {
                System.err.println("错误：同名文件存在，无法创建目录");
            }
        } else {
            boolean created = folder.mkdir();
            if (!created) {
                System.out.println("目录创建失败，请检查路径有效性");
            }
        }

        // 4. 处理文件上传
        try {
            String imageUrl = fileService.uploadImage(file, folderPath);

            result.put("code", 0);
            result.put("imageUrl", imageUrl);
            result.put("folderPath", folderPath); // 返回文件夹路径
        } catch (Exception e) {
            result.put("code", -1);
            result.put("message", "文件上传异常: " + e.getMessage());
        }
        return result;
    }


    @ApiOperation(value = "下载文件")
    @GetMapping(value = "/downloadZip")
    public void downloadZip(@RequestParam(value = "imageUrl") String imageUrl, HttpServletResponse response) {
        try {
            if (imageUrl == null || imageUrl.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.setContentType("text/plain");
                response.getOutputStream().write("未提供有效文件".getBytes());
                return;
            }

            File file = new File(imageUrl);//创建指定目录和文件名称的文件对象
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setContentType("text/plain");
                response.getOutputStream().write("文件不存在".getBytes());
                return;
            }

            // 设置响应头
            response.setContentType("application/zip");
            String fileName = "download.zip"; // 可根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            FolderToZipUtil.zip(imageUrl, response);
            response.flushBuffer();
        }   catch (Exception e) {
            e.printStackTrace();
            if (!response.isCommitted()) {
                response.resetBuffer();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("text/plain");
                try {
                    response.getOutputStream().write(("压缩文件时发生错误: " + e.getMessage()).getBytes());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
